<template>
  <div class="app-container">
    <!--    表单-->
    <el-form v-if="active==1" ref="form" :model="chargeForm" :rules="formRules" label-width="80px">
      <el-form-item label="标题" prop="detailName">
        <el-input v-model="chargeForm.detailName" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label=" 费用单位" prop="unit">
        <el-select v-model="chargeForm.unit" placeholder="选择费用单位" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="  计费方式" prop="charge">
        <el-select v-model="chargeForm.charge" placeholder="选择计费方式" clearable size="small">
          <el-option
            v-for="dict in Options"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单价" prop="money">
        <el-input type="number" v-model.number="chargeForm.money" name="money" />
      </el-form-item>
      <el-form-item label="订金" prop="deposit">
        <el-input type="number" v-model.number="chargeForm.deposit" />
      </el-form-item>
      <el-form-item label="注意事项" prop="attention">
        <el-input v-model="chargeForm.attention" placeholder="请输入注意事项" />
      </el-form-item>
      <el-form-item label="描述" prop="description" style="width: 100%;height: 300px">
        <Editor v-model="chargeForm.description" />
      </el-form-item>

      <!--      <el-form-item label=""  style="margin-top: 50px" >-->
      <!--        <el-button type="primary" @click="submitChargeForm">确 定</el-button>-->
      <!--      </el-form-item>-->
    </el-form>

    <!--    checkbox-->
    <el-form ref="queryForm" :inline="false" label-width="68px" v-if="sysAttribute.length>0">
      <el-row>
        <el-col :span="24">
          <el-form-item v-for="(items,i) in sysAttribute" :key="i" :label="items.name">
            <el-checkbox-group v-model="checkboxArr[i]">
              <el-checkbox
                v-for="(items2,i2) in items.alternativeList"
                :key="i2"
                :label="items2"
                border
              ></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item size="large" v-if="sysAttribute.length>0">
            <el-button type="primary" @click="getNow">生成分类属性</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!--    表格-->
    <el-table v-if="tableList.length>0" :data="tableList">
      <el-table-column label="序号" type="index" show-overflow-tooltip width="50"></el-table-column>
      <el-table-column
        v-for="(items,i) in tableHeader"
        :key="i"
        :label="items"
        align="center"
        :prop="items"
      ></el-table-column>
      <!--        priceList-->
      <el-table-column label="价格￥">
        <template slot-scope="scope">
          <el-input
            v-show="scope.$index==i"
            v-for="(items,i) in priceList"
            :key="i"
            v-model="priceList[i]"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:sku:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--    <el-form  v-if="tableList.length>0"  :inline="false" label-width="68px" style="margin: 25px 0px" >-->
    <!--      <el-row >-->
    <!--        <el-col :span="24" >-->
    <!--          <el-form-item size="large">-->
    <!--            <el-button type="primary" @click="updateList">提交生成参数</el-button>-->
    <!--          </el-form-item>-->
    <!--        </el-col>-->
    <!--      </el-row>-->
    <!--    </el-form>-->
    <!--    -->

    <el-form :inline="false" label-width="68px" style="margin: 25px 0px">
      <el-row>
        <el-col :span="24">
          <el-form-item size="large">
            <el-button type="primary" @click="submitAll('form')">提交生成参数</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {
  getInfoTypeDetailId,
  getInfoTypeNoDetailId,
  listSku,
  getSku,
  delSku,
  addSku,
  updateSku,
  exportSku,
  allSku
} from "@/api/system/type/sku";
import Editor from "@/components/Editor";
import {
  list,
  listType,
  getType,
  delType,
  addType,
  updateType,
  exportType,
  treeselect
} from "@/api/system/type";
import {
  listDetail,
  getDetail,
  delDetail,
  addDetail,
  updateDetail,
  exportDetail
} from "@/api/system/detail";
import Treeselect from "@riophae/vue-treeselect";

export default {
  name: "Sku",
  components: {
    Editor
  },
  data() {
    return {
      // 上传底部列表
      postList: [],
      formRules: {
        detailName: [
          { required: true, message: "不能为空！", trigger: "blur" }
        ],
        unit: [{ required: true, message: "不能为空！", trigger: "blur" }],
        charge: [{ required: true, message: "不能为空！", trigger: "blur" }],
        money: [{ required: true, message: "不能为空！", trigger: "blur" }],
        deposit: [{ required: true, message: "不能为空！", trigger: "blur" }],
        attention: [{ required: true, message: "不能为空！", trigger: "blur" }],
        description: [
          { required: true, message: "不能为空！", trigger: "blur" }
        ]
      },
      number: [{ required: true, message: "请输入数字" }],
      active: 1,
      boxForm: {},
      statusOptions: [],
      Options: [],
      //存放表格数据
      sysTypeDetail: [],
      //判断新增还是修改   true   修改    false  新增
      flag: undefined,
      //价格数组
      priceList: [],
      tableHeader: [],
      tableList: [],
      //删除空数组下标集合
      deleteIndex: [],
      //表头
      // tableHeader:[],
      //多选框内容数组
      sysAttribute: [],
      checkboxArr: [],
      // typeDetailId
      typeDetailId: -1,
      typeId: -1,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 规格表格数据
      skuList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // skuId: undefined,
        // data: undefined,
        typeId: this.$route.params.typeId,
        typeDetailId: this.$route.params.typeDetailId
      },
      // 表单参数
      form: {},
      // 第二个表单参数
      chargeForm: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getDicts("sys_cost_unit").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_mode").then(response => {
      this.Options = response.data;
    });

    this.typeId = this.$route.params.typeId;
    var typeDetailId = this.$common.getlocalStorage("typeDetailId");
    this.typeDetailId = typeDetailId;

    //  //判断新增还是修改   true   修改    false  新增
    if (!!typeDetailId) {
      this.flag = true;
    } else {
      this.flag = false;
    }

    console.log("typeId", this.typeId);
    console.log("typeDetailId", typeDetailId);

    this.getList();
  },
  watch: {
    checkboxArr(newValue, oldValue) {
      var deleteIndex = [];
      newValue.forEach((items, i) => {
        if (items.length == 0) {
          deleteIndex.push(i);
        }
      });
      console.log(deleteIndex);
      this.deleteIndex = deleteIndex;
      console.log(newValue);
    },
    priceList(newValue, oldValue) {
      console.log(newValue);
    }
  },
  methods: {
    //提交所有
    submitAll(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // alert('submit!');
          console.log("1form表单", this.chargeForm);

          var sysTypeDetail = this.chargeForm;
          sysTypeDetail.typeId = this.typeId;
          //多选框内容
          console.log("2多选框", this.sysAttribute);

          this.updateList();
          var sysSku = this.postList;

          var postObj = { sysTypeDetail, sysSku };

          // 多选表格价格
          // if(this.sysAttribute)
          if (this.postList.length != this.priceList.length) {
            this.msgError("参数不完整！");
          } else {
            // /system/sku/allSku   修改规格
            allSku(postObj).then(res => {
              console.log("修改规格返回值", res);
              this.msgSuccess("修改成功");
              this.$common.setlocalStorage(
                "typeDetailId",
                res.data.typeDetailId
              );
              this.typeDetailId = res.data.typeDetailId;
              this.$router.push(`/service/type`);
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //提交表单
    updateList() {
      // console.log()
      var postList = [];

      this.priceList.forEach((items, i) => {
        var obj = {
          typeDetailId: this.typeDetailId,
          data: JSON.stringify(this.tableList[i]),
          money: items
        };
        postList.push(obj);
      });

      //postList[0]={typeDetailId :this.typeDetailId,}

      console.log("传递参数", postList);
      console.log(this.flag);
      this.postList = postList;
      // // this.tableList
      // if(postList.length!=this.tableList.length){
      //   this.msgError('参数不完整！');
      // }else {
      //   if(this.flag==true){
      //     //  修改
      //     // console.log(postList)
      //     if (postList.length==0) postList[0]={typeDetailId :this.typeDetailId,}
      //     updateSku(postList).then(response => {
      //       console.log(response)
      //       if (response.code === 200) {
      //         this.msgSuccess("更改成功");
      //         // this.open = false;
      //         // this.getList();
      //       } else {
      //         this.msgError(response.msg);
      //       }
      //     });
      //   } else if(this.flag==false){
      //     //  新增
      //     addSku(postList).then(response => {
      //       console.log(response)
      //       if (response.code === 200) {
      //         this.msgSuccess("更改成功");
      //         // this.open = false;
      //         // this.getList();
      //       } else {
      //         this.msgError(response.msg);
      //       }
      //     });
      //   }
      // }
    },
    //生成分类属性
    getNow() {
      // this.reset()
      this.priceList.length = 0;
      console.log("checkboxArr", this.checkboxArr);
      console.log("sysAttribute", this.sysAttribute);
      console.log("tableHeader", this.tableHeader);

      var checkboxArr = []; //存放筛选后的数组
      this.checkboxArr.forEach((items, i) => {
        if (items.length != 0) checkboxArr.push(items);
      });
      console.log(this.doExchange(checkboxArr));

      var arr = [];
      this.sysAttribute.forEach((items, index) => {
        console.log(this.IsInArray(this.deleteIndex, index.toString()));
        if (this.IsInArray(this.deleteIndex, index.toString()) == true) {
          //     true
        } else {
          //    false
          arr.push(items.name);
        }
      });
      this.tableHeader = arr;
      console.log("标题数组", arr);
      console.log(this.tableHeader);
      var posArr = [];
      console.log(checkboxArr);
      if (checkboxArr.length > 1) {
        //如果checkbox列表选择多行
        this.doExchange(checkboxArr).forEach((items, i) => {
          var postObj = {};
          console.log(items);
          items.forEach((items2, i2) => {
            postObj[arr[i2]] = items2;
          });
          posArr.push(postObj);
        });
      } else {
        //如果checkbox列表只有一行
        var postObj = {};
        var oneCheckArr = [];
        if (!!checkboxArr[0]) {
          checkboxArr[0].forEach((items1, i1) => {
            var arr = [];
            // oneCheckArr[i1]=items1
            arr[0] = items1;
            oneCheckArr[i1] = arr;
          });
          console.log("oneCheckArr", oneCheckArr);
          oneCheckArr.forEach((items, i) => {
            var Obj = {
              [arr[0]]: items
            };
            posArr.push(Obj);
          });
        } else {
          this.msgError("参数不完整！");
        }
      }

      console.log(postObj);
      // console.log(posArr)
      this.tableList = posArr;

      this.priceList.length = this.tableList.length;
    },

    /** 查询规格列表 */
    getList() {
      this.checkboxArr.length = 0;
      this.loading = true;
      this.sysTypeDetail.length = 0;
      this.chargeForm = {};

      // if (!!this.typeDetailId) {
      // if (this.flag==true){
      //  修改   调取整体数据接口
      //  getInfoTypeDetailId
      var typeDetailId;
      if (!!this.typeDetailId) {
        typeDetailId = this.typeDetailId;
      } else {
        typeDetailId = 0;
      }
      getInfoTypeDetailId(this.typeId, typeDetailId).then(response => {
        console.log("整体数据接口返回值", response.data);
        //  表单赋值
        if (!!response.data.sysTypeDetail)
          this.chargeForm = response.data.sysTypeDetail;
        //多选框内容
        this.sysAttribute = response.data.sysAttribute;

        // 底部表单
        // if(!!response.data.sysTypeDetail)  this.chargeForm =  response.data.sysTypeDetail
        this.sysAttribute.forEach((items, i) => {
          var name = [];
          this.checkboxArr.push(name); //用于存放数组的选中状态数组
          var strs = new Array(); //定义一数组
          //字符串转数组
          if (items.alternative.search(",") == -1) {
            //  没有逗号
            strs.push(items.alternative);
          } else {
            //  有逗号
            strs = items.alternative.split(","); //字符分割
          }
          items.alternativeList = strs;
        });
        this.sysTypeDetail.push(response.data.sysTypeDetail);
        // if(!!response.data.sysTypeDetail){
        //   this.sysTypeDetail.push(response.data.sysTypeDetail)
        // }else {
        //   this.sysTypeDetail.push([])
        // }
        console.log(this.sysTypeDetail);

        //  生成列表取值
        //中间表格
        var typeDetailId = this.$common.getlocalStorage("typeDetailId");
        if (!!typeDetailId) {
          this.queryParams.typeDetailId = typeDetailId;
          listSku(this.queryParams)
            .then(response => {
              console.log("规格列表list", response.rows);
              if (response.rows.length > 0) {
                //有值  修改
                this.flag = true;
              } else {
                //没有值 新增
                this.flag = false;
              }
              this.loading = false;
              // this.skuList = response.rows;
              // this.total = response.total;

              // tableHeader   表头
              var header = JSON.parse(response.rows[0].data);
              this.tableHeader = Object.keys(header);
              //表格数据
              var tableList = [];
              var dataArr = [];
              this.priceList.length = 0;
              response.rows.forEach((items, i) => {
                // priceList  价格数组
                this.priceList.push(items.money);
                // dataArr =
                dataArr.push(Object.values(JSON.parse(items.data)));
              });
              console.log("", dataArr);

              //dataArr  value
              //   this.tableHeader  key
              dataArr.forEach((items1, i1) => {
                var objOuter = {};
                console.log(items1);
                this.tableHeader.forEach((items, i) => {
                  objOuter[items] = items1[i];
                });
                tableList.push(objOuter);
              });
              console.log("表格数据", tableList);
              this.tableList = tableList;
            })
            .catch(err => {
              console.log(err);
            });
        }
      });

      //   // }else if(this.flag==false){
      //   //   //  新增
      //   //   //  不动
      //   // }
      // }else{
      // if (this.flag==true){
      //  修改   调取整体数据接口
      //  getInfoTypeDetailId
      // getInfoTypeNoDetailId(parseInt(this.typeId)).then(response => {

      //   console.log("整体数据接口返回值", response.data);
      //   //  表单赋值
      //   if (!!response.data.sysTypeDetail)
      //     this.chargeForm = response.data.sysTypeDetail;
      //   //多选框内容
      //   this.sysAttribute = response.data.sysAttribute;

      //   // 底部表单
      //   // if(!!response.data.sysTypeDetail)  this.chargeForm =  response.data.sysTypeDetail
      //   this.sysAttribute.forEach((items, i) => {
      //     var name = [];
      //     this.checkboxArr.push(name); //用于存放数组的选中状态数组
      //     var strs = new Array(); //定义一数组
      //     //字符串转数组
      //     if (items.alternative.search(",") == -1) {
      //       //  没有逗号
      //       strs.push(items.alternative);
      //     } else {
      //       //  有逗号
      //       strs = items.alternative.split(","); //字符分割
      //     }
      //     items.alternativeList = strs;
      //   });
      //   this.sysTypeDetail.push(response.data.sysTypeDetail);
      //   // if(!!response.data.sysTypeDetail){
      //   //   this.sysTypeDetail.push(response.data.sysTypeDetail)
      //   // }else {
      //   //   this.sysTypeDetail.push([])
      //   // }
      //   console.log(this.sysTypeDetail);

      //   //  生成列表取值
      //   //中间表格
      //   var typeDetailId = this.$common.getlocalStorage("typeDetailId");
      //   if (!!typeDetailId) {
      //     this.queryParams.typeDetailId = typeDetailId;
      //     listSku(this.queryParams)
      //       .then(response => {
      //         console.log("规格列表list", response.rows);
      //         if (response.rows.length > 0) {
      //           //有值  修改
      //           this.flag = true;
      //         } else {
      //           //没有值 新增
      //           this.flag = false;
      //         }
      //         this.loading = false;
      //         // this.skuList = response.rows;
      //         // this.total = response.total;

      //         // tableHeader   表头
      //         var header = JSON.parse(response.rows[0].data);
      //         this.tableHeader = Object.keys(header);
      //         //表格数据
      //         var tableList = [];
      //         var dataArr = [];
      //         this.priceList.length = 0;
      //         response.rows.forEach((items, i) => {
      //           // priceList  价格数组
      //           this.priceList.push(items.money);
      //           // dataArr =
      //           dataArr.push(Object.values(JSON.parse(items.data)));
      //         });
      //         console.log("", dataArr);

      //         //dataArr  value
      //         //   this.tableHeader  key
      //         dataArr.forEach((items1, i1) => {
      //           var objOuter = {};
      //           console.log(items1);
      //           this.tableHeader.forEach((items, i) => {
      //             objOuter[items] = items1[i];
      //           });
      //           tableList.push(objOuter);
      //         });
      //         console.log("表格数据", tableList);
      //         this.tableList = tableList;
      //       })
      //       .catch(err => {
      //         console.log(err);
      //       });
      //   }
      // });

      // }else if(this.flag==false){
      //   //  新增
      //   //  不动
      // }
      // }
    },
    submitChargeForm() {
      console.log("表单提交参数", this.chargeForm);
      if (this.flag == true) {
        //修改
        updateDetail(this.chargeForm).then(response => {
          if (response.code === 200) {
            this.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          } else {
            this.msgError(response.msg);
            this.getList();
          }
        });
      } else if (this.flag == false) {
        //  新增
        this.chargeForm.typeId = this.typeId;
        this.chargeForm.pageSize = 10;
        if (
          !!this.chargeForm.description &&
          !!this.chargeForm.attention &&
          !!this.chargeForm.money &&
          !!this.chargeForm.deposit &&
          !!this.chargeForm.detailName &&
          !!this.chargeForm.unit &&
          !!this.chargeForm.charge &&
          !!this.chargeForm.typeId
        ) {
          addDetail(this.chargeForm).then(response => {
            console.log(response);
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              this.$common.setlocalStorage(
                "typeDetailId",
                response.data.typeDetailId
              );
              this.flag = false; //改成修改

              // this.$router.push(`/fenleiInfo/type/data/${this.typeId}/${response.data.typeDetailId}`);
              // this.open = false;
              // this.typeId = response.data.typeId
              // this.typeDetailId = response.data.typeDetailId
              // this.$route.params.typeId = response.data.typeId
              // this.$route.params.typeDetailId = response.data.typeDetailId
              // this.getList();
            } else {
              this.msgError(response.msg);
              // this.getList();
            }
          });
        } else {
          console.log(this.chargeForm);
          this.msgError("参数不能为空或错误!");
        }
      }
    },

    //字典转换
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.unit);
    },
    Format(row, column) {
      return this.selectDictLabel(this.Options, row.charge);
    },

    /*返回组合的数组*/
    doExchange(arr) {
      var len = arr.length;
      // 当数组大于等于2个的时候
      if (len >= 2) {
        // 第一个数组的长度
        var len1 = arr[0].length;
        // if (len1==0 )
        // 第二个数组的长度
        var len2 = arr[1].length;
        // 2个数组产生的组合数
        var lenBoth = len1 * len2;
        //  申明一个新数组
        var items = new Array(lenBoth);
        // 申明新数组的索引
        var index = 0;
        for (var i = 0; i < len1; i++) {
          for (var j = 0; j < len2; j++) {
            if (arr[0][i] instanceof Array) {
              items[index] = arr[0][i].concat(arr[1][j]);
            } else {
              items[index] = [arr[0][i]].concat(arr[1][j]);
            }
            index++;
          }
        }
        var newArr = new Array(len - 1);
        for (var i = 2; i < arr.length; i++) {
          newArr[i - 1] = arr[i];
        }
        newArr[0] = items;
        return this.doExchange(newArr);
      } else {
        return arr[0];
      }
    },

    IsInArray(arr, val) {
      var testStr = "," + arr.join(",") + ",";
      return testStr.indexOf("," + val + ",") != -1;
    },

    transformObject(keyArr, valueArr) {
      var obj = {};
      keyArr.map((v, i) => {
        obj[keyArr[i]] = valueArr[i];
      });
      return obj;
    },
    // 表单重置
    reset() {
      this.form = {
        skuId: undefined,
        data: undefined,
        delFlag: undefined,
        moeny: undefined,
        typeDetailId: undefined
      };
      this.tableHeader = [];
      this.tableList = [];
      this.resetForm("form");
    },
    //  生成的表格删除一行
    /** 删除按钮操作 */
    handleDelete(row) {
      // const skuIds = row.skuId || this.ids;
      // this.$confirm('是否确认删除规格编号为"' + skuIds + '"的数据项?', "警告", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning"
      // }).then(function() {
      //   return delSku(skuIds);
      // }).then(() => {
      //   this.getList();
      //   this.msgSuccess("删除成功");
      // }).catch(function() {});

      console.log(row);
      this.tableList.forEach((items, i) => {
        if (items == row) {
          console.log(i);
          this.tableList.splice(i, 1);
          this.priceList.splice(i, 1);
          console.log(this.priceList);
        }
      });
    }
  }
};
</script>
